<?php


namespace App\Model;


class Articles extends Model
{
    protected ?string $table = 'articles';
    protected array $fillable = ['user_id','title','slug','content','summary','content_type','cover_image','status','view_count','like_count','comment_count','favorite_count','reading_time'];

    /**
     * 与tag表多对多关联
     * article_tag作为中间表
     * @return \Hyperf\Database\Model\Relations\BelongsToMany
     */
    public function tags()
    {
        return $this->belongsToMany(\App\Model\Tag::class, 'article_tag', 'article_id', 'tag_id');
    }

    /**
     * 与category表多对多关联
     * article_category作为中间表
     */
    public function categories()
    {
        return $this->belongsToMany(\App\Model\Category::class, 'article_category', 'article_id', 'category_id');
    }

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo(\App\Model\User::class, 'user_id');
    }

    /**
     * 关联点赞
     */
    public function likes()
    {
        return $this->hasMany(ArticleLike::class, 'article_id');
    }

    /**
     * 关联收藏
     */
    public function favorites()
    {
        return $this->hasMany(ArticleFavorite::class, 'article_id');
    }

    /**
     * 检查用户是否点赞
     * @param $userId
     * @return bool
     */
    public function isLikedByUser($userId): bool
    {
        return $this->likes()->where('user_id', $userId)->exists();
    }

    /**
     * 获取点赞总数
     * @return int
     */
    public function getLikesCount(): int
    {
        return $this->likes()->count();
    }

    /**
     * 检查用户是否收藏
     * @param $userId
     * @return bool
     */
    public function isFavoirtedByUser($userId): bool
    {
        return $this->favorites()->where('user_id', $userId)->exists();
    }


    /**
     * 获取收藏总数
     * @return int
     */
    public function getFavoritesCount(): int
    {
        return $this->favorites()->count();
    }
}